<template>
    <div class="container-article">

        <div v-if="show" class="articleDetail">
            <div class="article">
                <div class="img-container">
                    <img :src="articleDetail.article.cover.includes('http') ? articleDetail.article.cover : baseUrl + '/' + articleDetail.article.cover"
                        :title="articleDetail.article.summary" :alt="articleDetail.article.summary">
                </div>
                <!-- 文章主体 v-infinite-scroll="commentLoad" -->
                <div class="main ">
                    <div class="view-count" title="浏览量">{{ articleDetail.article.view_count }}</div>
                    <!-- +1动画 -->
                    <div class="floating-box" ref="floatingBox">
                        <el-tag type="primary">+1</el-tag>
                    </div>
                    <div class="title">
                        <div>
                            <el-tag style="margin-right: 10px;" v-for="(item) in articleDetail.categoryList"
                                :key="item.id" type="primary">{{ item.name }}</el-tag>
                        </div>
                        <div class="inner">
                            <p>{{ articleDetail.article.summary }}</p>
                        </div>
                        <h1>{{ articleDetail.article.title }}</h1>
                    </div>
                    <div class="editor-content-view" v-html="articleDetail.article.content"></div>
                    <el-divider>
                        评论
                    </el-divider>
                    <!-- 评论框 -->
                    <div class="commentContent">
                        <img v-if="userStore.isLoggedIn" :src="srcToPath(userStore.user.avatar)"
                            :alt="userStore.user.username" :title="userStore.user.username">
                        <el-input v-model="commentContent" placeholder="新的风暴已经出现，你的妙评何时再现" type="textarea" />
                        <el-button type="primary" @click="addComment">发表</el-button>
                    </div>
                    <div class="comment">
                        <!-- 评论区域显示 -->
                        <div v-if="commentList.length > 0">

                            <comment v-if="commentId" :comment="commentOne" />

                            <comment v-for="item in commentList" :key="item.commentId" :comment="item" />
                            <div :loading="commentLoading" v-if="commentList.length < commentModel.total" class="cursor"
                                @click="commentLoad">加载更多...</div>
                            <el-divider v-else>
                                <div>已加载全部...</div>
                            </el-divider>
                        </div>

                        <div v-else>
                            <el-empty description="暂无评论" />
                        </div>
                    </div>
                </div>

            </div>

            <div class="userInfo">
                <div class="user-card">
                    <div class="avatar">
                        <img :src="srcToPath(articleDetail.userInfo.avatar)" :alt="articleDetail.userInfo.username"
                            :title="articleDetail.userInfo.username">
                    </div>
                    <div class="user-info">
                        <h3 class="username">{{ articleDetail.userInfo.username }}</h3>
                        <p class="other-info">其他信息</p>
                    </div>
                </div>
                <!-- <div>
                    推荐内容
                </div> -->
                <div class="like">
                    <img @click="likeCollectHandle('like')"
                        :src="`${baseUrl}/uploads/static/${likeCollect.like ? '_' : ''}dianzan.png`" alt="点赞">
                    <img @click="likeCollectHandle('collect')"
                        :src="`${baseUrl}/uploads/static/${likeCollect.collect ? '_' : ''}shoucang.png`" alt="收藏">
                </div>
            </div>

        </div>
        <div style="text-align: center;" v-else>
            <el-empty description="description"> {{ pageMessge }} </el-empty>
        </div>


    </div>
</template>
<script setup>
import { baseUrl } from '@/utils/http.js'
import { onMounted, ref, nextTick, unref, onUpdated, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { getArticleDetail, getLikeCollect, addLike, addCollect } from '@/api/article'
import { getArticleComment, addArticleComment, getCommentById, } from '@/api/comment'
import comment from '../components/comment.vue';
import srcToPath from '@/utils/srcToPath.js'
const router = useRouter()
const route = useRoute()
console.log(route.params);
import useUserStore from '@/pinia/userStore'
import { ElMessage } from 'element-plus';
const userStore = useUserStore()
// 当前页面是否正常访问
const show = ref(true)
// 页面提示信息
const pageMessge = ref('')
// 拿到当前文章的id
const id = ref(null)
// 评论id
const commentId = ref(null)
const commentOne = ref({})
id.value = route.params.id
// 文章详情
const articleDetail = ref({
    article: { cover: '' }, userInfo: {}
})

// 评论
const commentContent = ref("")
// 点赞和收藏对象
const getLikeAndCollect = async () => {
    // 获取点赞数据
    const { data } = await getLikeCollect({ id: id.value })
    likeCollect.value = data
}
// 查询文章的详情信息
const init = async () => {
    id.value = route.params.id
    if (route.params.commentId) {
        commentId.value = route.params.commentId
        // 获取一条评论
        const res = await getCommentById(commentId.value)
        commentOne.value = res.data
        console.log(res);
    }
    // 判断id
    if (!Number.isInteger(Number(id.value))) {
        show.value = false
        pageMessge.value = '页面信息错误，3秒后返回主页...'
        setTimeout(() => {
            router.push('/')
        }, 3000)
        return
    }

    // 请求数据
    const res = await getArticleDetail(id.value)
    articleDetail.value = res.data
    console.log(res);

    if (userStore.isLoggedIn) {
        getLikeAndCollect()
    }



    nextTick(() => {
        console.log("播放");
        floatingBox.value.classList.add('animate');
        setTimeout(() => {
            articleDetail.value.article.view_count++;
        }, 1100)
    })
}

const commentList = ref([

])
const commentModel = ref({
    pageSize: 5,
    pageNum: 1,
    desc: 'asc',
    articleId: null,
    total: 0,
})
const commentLoading = ref(true)
// 评论相关的内容
const commentLoad = async () => {
    if (commentList.length >= commentModel.total) {
        return
    }
    commentLoading.value = true
    commentModel.value.articleId = id.value
    const res = await getArticleComment(unref(commentModel))
    commentModel.value.total = res.data.total
    commentList.value.push(...res.data.comment)
    commentModel.value.pageNum++;
    commentLoading.value = false

}
// 添加评论
const addComment = async () => {
    if (!commentContent || commentContent.length == 0) {
        return ElMessage.info('请输入内容')
    }
    const res = await addArticleComment({ content: commentContent.value, article_id: id.value })
    if (res.status == 200) {
        ElMessage.success('发表评论成功')
        commentModel.value.pageNum = 1;
        commentList.value = []
        commentContent.value = ''
        commentLoad()
    }

}
let timer
const likeCollectHandle =  (e) => {
    if (userStore.isLoggedIn) {
        if(timer) {
            clearTimeout(timer)
        }
        timer = setTimeout(async()=>{
            if (e == 'like') {
            const res = await addLike({ id: id.value })
            console.log(res);
            if (res.status == 200) {
                ElMessage.success(res.message??"点赞成功")
            }
        } else {
            const res = await addCollect({ id: id.value })
            if (res.status == 200) {
                ElMessage.success(res.message??"收藏成功")
            }
        }
        getLikeAndCollect()
        },500)
        
    } else {
        ElMessage.info("请先登录")
    }

}


// function scrollToElement(id) {
//     const element = document.getElementById(id);
//     if (element) {
//         element.scrollIntoView({ behavior: 'smooth' }); // 平滑滚动到元素  
//     }
// }
init()
// const commentItem = JSON.parse(localStorage.getItem("comment" + id.value) ?? null)


const likeCollect = ref({
    like: false,
    collect: false,
})

const floatingBox = ref(null)
onMounted(() => {
    // if (commentItem) {
    //     commentItem.flag = true
    //     commentList.value.push(commentItem)
    // }
    // 过度动画播放
    commentLoad()

})
// console.log(router);
</script>


<style lang="scss" scoped>
// 定义变量
$imgHeight: 300px;

.container-article {
    width: 100%;
    height: calc(100vh - 60px);
    overflow-y: scroll;
    // padding-bottom: 50px;
}

.articleDetail {
    max-width: 1400px;
    margin: 0 auto;
    display: flex;
    justify-content: space-around;
    align-items: start;

    .article {
        width: 70%;
        position: relative;

        .main {
            position: absolute;
            top: 0;
            width: 100%;
            z-index: 11;

            .view-count {
                display: inline-flex;
                justify-content: center;
                align-items: center;
                border-radius: 0 0 0 20px;
                box-sizing: border-box;
                padding: 10px;
                // width: auto;
                // height: auto;
                position: absolute;
                right: 0;
                background-color: var(--el-text-color-primary);
                opacity: .6;
                color: var(--el-bg-color-page)
            }

            .title {
                padding: 0 20px;
                height: $imgHeight;
                display: flex;
                // align-items: self-end;
                flex-direction: column-reverse;

                h1 {
                    color: var(--el-text-color-primary);
                    padding: 0;
                    margin: 0;
                }

                p {
                    color: var(--el-text-color-regular)
                }
            }
        }

        .commentContent {
            // position: fixed;
            // bottom: 0;
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;

            img {
                width: 50px;
                height: 50px;
                border-radius: 50%;
                margin-right: 20px;
            }
        }
    }


    .img-container {
        position: relative;
        /* 确保伪元素可以相对于这个容器定位 */
        display: inline-block;
        /* 根据需要调整显示方式 */
        width: 100%;
    }

    .img-container img {
        display: block;
        /* 确保图片是块级元素 */
        width: 100%;
        height: $imgHeight;
        /* 图片宽度设置为容器宽度 */
        // height: auto;
        /* 图片高度自动调整 */
    }

    .img-container::before {
        content: "";
        /* 伪元素需要内容，即使它是空的 */
        position: absolute;
        /* 绝对定位相对于最近的定位祖先元素 */
        top: 30%;
        /* 伪元素顶部与容器顶部对齐 */
        left: 0;
        /* 伪元素左侧与容器左侧对齐 */
        right: 0;
        /* 伪元素右侧与容器右侧对齐 */
        bottom: 0;
        /* 伪元素底部与容器底部对齐 */
        background: linear-gradient(to bottom, transparent, var(--el-bg-color-page));
        /* 顶部透明到底部黑色的线性渐变 */
        z-index: 10;
        /* 将伪元素置于图片下方 */
        height: 70%;
    }

}

.userInfo {

    .user-card {
        width: 200px;
        border: 1px solid #ccc;
        border-radius: 5px;
        overflow: hidden;
        margin: 10px;
    }

    .avatar {
        width: 100%;
        padding-top: 100%;
        position: relative;
        // background-color: #f5f5f5;
    }

    .avatar img {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 80%;
        height: 80%;
        border-radius: 50%;
        object-fit: cover;
    }

    .user-info {
        padding: 10px;
    }

    .username {
        margin: 0;
        font-weight: bold;
    }

    .other-info {
        margin-top: 5px;
        font-size: 14px;
        color: #666;
    }
}

@media (max-width: 600px) {
    .articleDetail {
        display: flex;
        flex-direction: column-reverse;

        // width: 90%;
        .article {
            width: 90%;
            margin: 0 auto;
        }

        .commentContent {
            position: fixed;
            bottom: 40px;
            width: 90%;
        }
    }

    .userInfo {
        width: 100%;

        // display: none;
        .user-card {
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            width: 90%;
            margin: 0 auto;
        }

        .avatar {
            margin: 0 20px;
            padding: 0;
            width: 70px;
        }

        .avatar img {
            // position: absolute;
            // top: 50%;
            // left: 50%;
            // transform: translate(-50%, -50%);
            width: 70px;
            height: 70px;
            // border-radius: 50%;
            // object-fit: cover;
        }

        .like {
            position: relative;
            // top: 0;
            // right: 0;
            float: right;
        }

    }

}

.floating-box {
    width: 20px;
    /* 设置你想要的宽度 */
    height: 20px;
    /* 设置你想要的高度 */
    position: absolute;
    /* 为了使用 top 属性 */
    top: 20px;
    /* 初始位置 */
    right: -20px;
    transition: top 1.3s ease;
    /* 过渡效果：顶部位置变化1秒，缓动函数 */
    animation: fadeOut 1s 1.3s forwards;
    /* 动画效果：1秒后淡出，持续1秒，动画结束后保持最后一帧的状态 */
    opacity: 1;
    /* 初始不透明度 */
}

.floating-box.animate {
    top: -20px;
    /* 最终位置：向上飘动20px */
}


.editor-content-view {
    padding: 0 20px;

    ::v-deep img,
    video {
        width: 100% !important;
    }
}

@keyframes fadeOut {
    0% {
        opacity: 1;
    }

    100% {
        opacity: 0;
    }
}


.like {
    position: absolute;
    bottom: 50px;
    right: 10%;
    z-index: 99;
    width: 100px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 0;

    img {
        width: 30px;
        height: 30px;
    }
}
</style>
